package com.demo.borrow;

import com.demo.book.BookService;
import com.demo.common.constant.WebConstants;
import com.demo.common.model.Book;
import com.demo.common.model.Borrow;
import com.demo.common.util.StringUtil;
import com.demo.student.StudentService;
import com.jfinal.aop.Before;
import com.jfinal.aop.Inject;
import com.jfinal.core.Controller;
import com.jfinal.kit.Kv;
import com.jfinal.kit.StrKit;

import java.util.Date;

@Before(BorrowInterceptor.class)
public class BorrowController extends Controller {

    @Inject
    BorrowService borrowService;

    @Inject
    BookService bookService;

    @Inject
    StudentService studentService;

    public void index() {
        Kv cond=Kv.create();
        if(StrKit.notBlank(getPara("studentid"))){
            cond.set("studentid",getPara("studentid"));
        }
        if(StrKit.notBlank(getPara("bookid"))){
            cond.set("bookid",getPara("bookid"));
        }
        if(StrKit.notBlank(getPara("back"))){
            cond.set("isback",getPara("back"));
        }
        setAttr("borrowPage", borrowService.paginate(getParaToInt(0, 1), 10,Kv.by("cond",cond)));
        render("borrow.html");
    }

    public void add() {
        setAttr("students",studentService.findAll());
        setAttr("books", bookService.findAll());
    }

    /**
     * save 与 update 的业务逻辑在实际应用中也应该放在 serivce 之中，
     * 并要对数据进正确性进行验证，在此仅为了偷懒
     */
    @Before(BorrowValidator.class)
    public void save() {
        Borrow borrow=getBean(Borrow.class);
        borrow.setBookcopyid(bookService.findByBookId(borrow.getBookid()).getBookcopyid());
        borrow.setBorrowtime(StringUtil.dateFormat(new Date()));
        borrow.save();
        redirect("/borrow");
    }

    public void edit() {
        setAttr("students",studentService.findAll());
        setAttr("books", bookService.findAll());
        setAttr("borrow", borrowService.findById(getParaToInt()));
    }

    /**
     * save 与 update 的业务逻辑在实际应用中也应该放在 serivce 之中，
     * 并要对数据进正确性进行验证，在此仅为了偷懒
     */
    @Before(BorrowValidator.class)
    public void update() {
        Borrow borrow=getBean(Borrow.class);
        borrow.setBookcopyid(bookService.findByBookId(borrow.getBookid()).getBookcopyid());
        borrow.setBorrowtime(StringUtil.dateFormat(new Date()));
        borrow.update();
        redirect("/borrow");
    }

    public void delete() {
        borrowService.deleteById(getParaToInt());
        redirect("/borrow");
    }

    public void back(){
        Borrow borrow=new Borrow();
        borrow.setId(getParaToInt());
        borrow.setIsback(WebConstants.BACK);
        borrow.setBacktime(StringUtil.dateFormat(new Date()));
        borrow.update();
        redirect("/borrow");
    }
}
